﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using deviceManage.Models;
using deviceManage.vo;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using deviceManage.Filters;
using deviceManage.Tools;
using deviceManage.VO;

namespace deviceManage.Controllers
{
    /// <summary>
    /// 设备运维计划
    /// </summary>
    [CheckLoginAttribute]
    public class DevicePlanController : Controller
    {
        private readonly DeviceCtx _context;

        public DevicePlanController(DeviceCtx context)
        {
            _context = context;
        }

        public IActionResult Index()
        {

            //是否只读权限
            int? flag = HttpContext.Session.GetInt32("viewFlag");

            return View(Tuple.Create(flag));
        }


        //ajax 获取分页数据,
        public AjaxResult List(int page, int limit)
        {
            AjaxResult r = new AjaxResult();
            IQueryable<DevicePlan> query = _context.DevicePlan;
          
            if (!string.IsNullOrWhiteSpace(Request.Form["startTime"]))
            {
                DateTime start = DateTime.Parse(Request.Form["startTime"]);
                query = query.Where(p => p.StartTime >= start);
            }
            if (!string.IsNullOrWhiteSpace(Request.Form["endTime"]))
            {
                DateTime end = DateTime.Parse(Request.Form["endTime"]);
                query = query.Where(p => p.EndTime <= end);
            }

            r.Count = query.Count();
            r.Code = 0;
            try
            {
                r.Data = query.Include(p=>p.Project).Include(p=>p.Contract)
                .Skip((page - 1) * limit).Take(limit)
                .ToList();
            }
            catch (Exception e)
            {
                r.Msg = e.Message;
            }
            return r;
        }

        /// <summary>
        /// 显示设备入库页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(string id)
        {
            
            //项目
            var projectList = _context.Project.Where(p => p.Deleted == 0).OrderBy(p => p.SortOrder).ToList();
            //服务合同
            var buyContractList = _context.ServiceContract.Where(p => p.Deleted == 0).ToList();
           

            //获取model
            DevicePlan device = new DevicePlan();
            if (!string.IsNullOrWhiteSpace(id))
            {
                device = _context.DevicePlan.Single(p => p.Id == id);
                device.IsEdit = true;
            }
            else //自动生成ID
            {
                device.Id = System.Guid.NewGuid().ToString();
                device.IsEdit = false;
            }
            return View(Tuple.Create(device,  projectList, buyContractList));
        }



        /// <summary>
        /// 显示设备入库页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Detail(string id)
        {

            //项目
            var projectList = _context.Project.Where(p => p.Deleted == 0).OrderBy(p => p.SortOrder).ToList();
            //服务合同
            var buyContractList = _context.ServiceContract.Where(p => p.Deleted == 0).ToList();


            //获取model
            DevicePlan device = new DevicePlan();
            if (!string.IsNullOrWhiteSpace(id))
            {
                device = _context.DevicePlan.Single(p => p.Id == id);
                device.IsEdit = true;
            }
             
            return View(Tuple.Create(device, projectList, buyContractList));
        }



        /// <summary>
        /// 保存设备运维计划信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public AjaxResult Save(DevicePlan obj)
        {
            var exist = _context.DevicePlan.Any(p => p.Id == obj.Id);
            if (obj.Id == null || !exist)
            { //新增          
                obj.CreateTime = DateTime.Now;
                _context.Add(obj);
                _context.SaveChanges();                
            }
            else
            {
                DevicePlan device = _context.DevicePlan.Single(p => p.Id == obj.Id);
                device.ContractId = obj.ContractId;
                device.EndTime = obj.EndTime;
                device.Name = obj.Name;
                device.ProjectId = obj.ProjectId;
                device.Remark = obj.Remark;
                device.StartTime = obj.StartTime;
                device.User = obj.User;
                device.UserParticipate = obj.UserParticipate;                 
                this._context.SaveChanges(); //保存                
            }

            //首先删除
            var deleteTimes = _context.DevicePlanTime.Where(p => p.PlanId == obj.Id);
            foreach(var item in deleteTimes)
            {
                _context.DevicePlanTime.Remove(item);
            }            
            _context.SaveChanges();

            //保存计划执行年月
            string month = Request.Form["month[]"];
            if(month != null)
            {
                string[] monthList = month.Split(",");
                foreach(string m in monthList)
                {
                    DevicePlanTime time = new DevicePlanTime();
                    time.PlanId = obj.Id;
                    time.PlanYear = int.Parse(m.Split("_")[0]);
                    time.PlanMonth = int.Parse(m.Split("_")[1]);
                    _context.DevicePlanTime.Add(time);
                }
                _context.SaveChanges();
            }

            return AjaxResult.GetOK("保存成功");
        }

        /// <summary>
        ///  选择设备
        /// </summary>
        /// <param name="id">设备ID</param>
        /// <returns></returns>
        public IActionResult SelectDevice(string id)
        {
            //下拉列表
            var typeList = _context.DeviceType.Where(p => p.Deleted == 0).OrderBy(p => p.SortOrder).ToList();
            return View(Tuple.Create(id,typeList));
        }


        /// <summary>
        /// 获取设备列表，用于添加设备到计划中
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="name">设备名称</param>
        /// <param name="id">计划ID</param>
        /// <returns></returns>
        public AjaxResult SelectDeviceList(int page, int limit, String name,string id,String deviceTypeId,String deviceId)
        {
            AjaxResult r = new AjaxResult();
            var q = _context.Device.FromSql($"select t1.*  from device t1 left join device_plan_items t2 on t1.id = t2.device_id and t2.plan_id = {id}  where t2.id is null");

            if (!string.IsNullOrWhiteSpace(name))
            {
                q = q.Where(p=>p.Name.Contains(name));
            }

            if (!string.IsNullOrWhiteSpace(deviceTypeId))
            {
                q = q.Where(p => p.DeviceTypeId == deviceTypeId);
            }

            if (!string.IsNullOrWhiteSpace(deviceId))
            {
                q = q.Where(p => p.DeviceId == deviceId);
            }

            r.Data = q.Include(p=>p.DeviceType).Include(p=>p.Room).ToList();
            return r;
        }

        /// <summary>
        /// 获取运维计划中的设备列表
        /// </summary>      
        /// <param name="id">计划ID</param>
        /// <returns></returns>
        public AjaxResult PlanDeviceList(string id)
        {
            AjaxResult r = new AjaxResult();
            IQueryable<DevicePlanItem> query = _context.DevicePlanItem.Where(p=>p.PlanId == id);             
            r.Count = query.Count();
            r.Code = 0;
            try
            {
                r.Data = query.Include(p => p.Device).ThenInclude(p=>p.DeviceType).ToList();
            }
            catch (Exception e)
            {
                r.Msg = e.Message;
            }
            return r;
        }

        public AjaxResult DeleteDevice(string id)
        {
            var device = _context.DevicePlanItem.Single(p => p.Id == id);
            _context.DevicePlanItem.Remove(device);
            _context.SaveChanges();

            return AjaxResult.GetOK("删除成功！");

        }

        /// <summary>
        /// 添加设备到计划中
        /// </summary>
        /// <param name="deviceId">设备ID</param>
        /// <param name="planId">计划ID</param>
        /// <returns></returns>
        public AjaxResult AddDeviceToPlan(string deviceId,string planId)
        {
            DevicePlanItem item = new DevicePlanItem();
            item.DeviceId = deviceId;
            item.PlanId = planId;
            item.CreateTime = DateTime.Now;
            item.CreateUserId = HttpContext.Session.GetString(WebContext.SESSION_KEY_USER_ID);

            _context.DevicePlanItem.Add(item);
            _context.SaveChanges();

            return AjaxResult.GetOK("添加成功！");

        }

        /// <summary>
        /// 获取设备计划的执行时间
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AjaxResult GetPlanTimes(string id)
        {
            AjaxResult result = new AjaxResult();
            result.Data = _context.DevicePlanTime.Where(p=>p.PlanId == id).ToList();
            return result;
        }

        /// <summary>
        /// 删除运维计划
        /// </summary>
        /// <returns></returns>
        public AjaxResult Delete(string id)
        {           

            //首先删除设备
            var times = _context.DevicePlanTime.Where(p => p.PlanId == id).ToList();
            foreach(var item in times)
            {
                _context.DevicePlanTime.Remove(item);
            }

            //删除时间
            var items = _context.DevicePlanItem.Where(p => p.PlanId == id).ToList();
            foreach (var item in items)
            {
                _context.DevicePlanItem.Remove(item);
            }

            //删除计划
            var device = _context.DevicePlan.Single(p => p.Id == id);
            _context.DevicePlan.Remove(device);

            _context.SaveChanges();

            return AjaxResult.GetOK("删除成功！");
        }
    }

    
}